package com.magelink;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.magelink.config.IsvConfig;
import com.magelink.core.ResponseMsg;
import com.magelink.pojo.IsvInstance;
import com.magelink.service.IsvService;
import com.magelink.util.SecureUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;


/**
 * 接入华为云市场实现新购商品 商品续费 商品过期 商品资源释放 商品升级
 * 文档:https://support.huaweicloud.com/accessg-marketplace/zh-cn_topic_0070649013.html
 *
 * @author 梁卓
 */
@Api(tags = "saas商品接入")
@RequestMapping("isv/")
@RestController
@AllArgsConstructor
@Slf4j
public class IsvController {

    @Autowired
    private IsvService isvService;

    @Autowired
    private  IsvConfig isvConfig;

    @ApiOperation("saas商品接入,华为云市场在客户购买商品后,将请求本接口")
    @GetMapping("marketplace/saas")
    public String instance(IsvInstance instance, HttpServletResponse response) {
        ResponseMsg responseBody = isvService.instance(instance);
        String signature = null;
        String jsonStr = null;
        try {
     // service返回的响应转换为json字符串
            jsonStr = JSONUtil.toJsonStr(responseBody);
     // 对响应json字符串进行签名
            signature = SecureUtils.generateResponseBodySignature(isvConfig.getAccessKey(), jsonStr);
        } catch (Exception e) {
            log.error("生成响应body签名异常:{}", ExceptionUtil.getMessage(e));
        }
     // 签名放入HttpServletResponse 响应头
        response.addHeader("Body-Sign", "sign_type=\"HMAC-SHA256\"" + "," + "signature=" + "\"" + signature + "\"");
        return jsonStr;
    }

    /**
     * 新购场景，
     */
    @Test
    @GetMapping("/itemAdd")
   public void itemAdd(IsvInstance isvInstance){
        String authToken = isvInstance.getAuthToken();
        System.out.println(authToken);

    }

}
